package com.hao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hao.eduservice.client.VodClient;
import com.hao.eduservice.entity.EduVideo;
import com.hao.eduservice.mapper.EduVideoMapper;
import com.hao.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hao.servicebase.exceptionhandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author hao
 * @since 2020-12-02
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper();
        wrapper.eq("course_id",courseId);

        List<EduVideo> eduVideos = this.list(wrapper);
        List<String> videoIds = new ArrayList<>();
        for (EduVideo video:eduVideos){
            String videoSourceId = video.getVideoSourceId();
            if (StringUtils.isNotEmpty(videoSourceId)){
                videoIds.add(videoSourceId);
            }
        }
        if(videoIds.size() > 0){
            vodClient.deleteAliVideos(videoIds);
        }
        boolean b = this.remove(wrapper);
        if(!b){
            throw new GuliException(20001,"删除课程小节失败");
        }
    }

    @Override
    public void deleteVideo(String videoId) {
        //获取视频id
        EduVideo eduVideo = this.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(StringUtils.isNotEmpty(videoSourceId)){
            //远程调用vod删除视频
            vodClient.removeAliVideo(videoSourceId);
        }
        //删除小节本身
        this.removeById(videoId);
    }
}
